package com.ysq.controller.exception;

import com.ysq.controller.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * ClassName: ProjectExceptionAdvice
 * Package: com.ysq.controller.exception
 * Description: 全局异常处理器
 *
 * @Author YSQ
 * @Create 2023/1/2 - 12:13
 */
@RestControllerAdvice //当前类为REST风格对应的异常处理器
@Slf4j //发送日志看异常信息
public class ProjectExceptionAdvice {
    /**
     * SQL异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());//输出日志查看异常信息
        //以用户名zhangsan为例会输出: Duplicate entry 'zhangsan' for key 'idx_username'

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }

        return Result.error("未知错误");
    }

    /**
     * 业务异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());//输出日志查看异常信息

        return Result.error(ex.getMessage());
    }
}
